package jsu.xnm.evelyn.controller;

import jsu.xnm.evelyn.util.FileUtil;
import jsu.xnm.evelyn.util.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;


/**
 * @author xnm
 * @version 1.0
 */
@RestController
@RequestMapping("/file")
public class FileUploadAndDownLoadController {

//    @Value("${evelyn.image.base-path}")
//    private String loadImgUrl;

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        String path = ResourceUtils.getURL("classpath:").getPath();

        String dateDir = FileUtil.makeFileDir();//文件存放的日期目录 如：2023/01/01
        System.out.println("dir= " +dateDir);
        String fullDir = path+FileUtil.UPLOAD_FILE_DIRECTORY+dateDir;
        System.out.println("fullDir= " +fullDir);
        File file = new File(fullDir);

        if(!file.exists()){
            file.mkdirs();
        }

        String absolutePath = file.getAbsolutePath();//图片存放绝对路径
        String absoluteFileName = null;
        if(!multipartFile.isEmpty()){
            String originalFilename = multipartFile.getOriginalFilename();
            absoluteFileName = FileUtil.makeFilePrefix(originalFilename);//文件全名
            multipartFile.transferTo(new File(absolutePath,absoluteFileName));
        }
        //todo: 文件上传
        return Result.success(dateDir+"/"+absoluteFileName);
    }
}
